package net.springmvc17_18.controller;

import net.springmvc17_18.entity.Stu;
import net.springmvc17_18.service.StuService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Controller
@ResponseBody
public class MyController {

    @GetMapping("my")
    @ResponseBody
    public String handler() {
        int a = 10 / 0;
        return "index";
    }

    @GetMapping("interceptor")
    public String interceptor() {
        System.out.println("排除这个路径");
        return "hh";
    }

    @Autowired
    private StuService stuService;

    @GetMapping("/login")
    public String login(@RequestParam String name,
                        @RequestParam String sn,
                        HttpSession session) {
        Stu stu = stuService.login(name, sn);
        if (Objects.nonNull(stu)) {
            session.setAttribute("stu", stu);
            return "hh";
        }
        return "login";
    }

    @PostMapping("upload")

    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpSession session) throws IOException {

        request.setCharacterEncoding("utf-8");
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        String realPath = session.getServletContext().getRealPath("/");
        System.out.println(realPath);
        File file1 = new File(realPath, originalFilename);
        file.transferTo(file1);
        return  file1.getAbsolutePath();
    }
    @GetMapping("filedown")
    public void filedown(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/html;charset=utf-8");
            File file = new
                    File(request.getSession().getServletContext().getRealPath("/"), "11.txt");
            System.out.println("文件：" + file.getAbsolutePath());
            byte[] data = FileUtils.readFileToByteArray(file);
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment;filename=" + new
                    String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.getOutputStream().write(data);
    }
}
